import React, { useState, useEffect } from 'react';
import { List, Card } from 'antd';
import { reqCategory } from '../../api';
import { BASE_IMG_URL } from '../../utils/constants';
import LinkButton from "../../components/link-button";
import { useLocation, useNavigate } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons'; // 导入具体的图标

const ProductDetail = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [cName1, setCName1] = useState('');  // 一级分类名称
  const [cName2, setCName2] = useState('');  // 二级分类名称
  // 从路由 state 中解构商品数据（其他页面跳转时传递过来）
  const { categoryId, pCategoryId, name, desc, price, imgs, detail } = location.state;

  //获取分类名称
  const getCategoryName = async () => {
    if (pCategoryId === '0') {
      // 获取一级分类名称
      const result = await reqCategory(categoryId); // 调用接口获取分类名称
      const cName = result.data.name;
      setCName1(cName); // 保存一级分类名称
    } else {
      // 情况 2：当前分类是二级分类
      // 一次发多个请求，等所有请求都返回后一起处理
      //  同时发送两个请求：获取父分类（一级）和当前分类（二级）的名称
      const results = await Promise.all([
        reqCategory(pCategoryId), // 父分类（一级）的名称
        reqCategory(categoryId)]); // 当前分类（二级）的名称
      const result1 = results[0];
      const result2 = results[1];
      const c1 = result1.data.name;  // 父分类名称
      const c2 = result2.data.name;  // 当前分类名称
      setCName1(c1);
      setCName2(c2);
    }
  };

  useEffect(() => {
    getCategoryName();
  }, []);

  const title = (
    <span>
      <LinkButton onClick={() => navigate(-1)}>
        <ArrowLeftOutlined style={{ fontSize: 20 }} />
      </LinkButton>
      商品详情
    </span>
  );

  const imgStyle = { width: 150, height: 150, marginRight: 10, border: '1px solid black' };

  return (
    <Card className='product-detail' title={title}>
      <List>
        <List.Item>
          <span className='left'>商品名称:</span>
          <span>{name}</span>
        </List.Item>
        <List.Item>
          <span className='left'>商品描述:</span>
          <span>{desc}</span>
        </List.Item>
        <List.Item>
          <span className='left'>商品价格:</span>
          <span>{price + '元'}</span>
        </List.Item>
        <List.Item>
          <span className='left'>所属分类:</span>
          <span>{cName1 + (cName2 ? ' --> ' + cName2 : '')}</span>
        </List.Item>
        <List.Item>
          <span className='left'>商品图片:</span>
          <span>
            {imgs.map(img => (
              <img src={BASE_IMG_URL + img}
                alt="img"
                key={img}
                style={imgStyle} />
            ))}
          </span>
        </List.Item>
        <List.Item>
          <span className='left'>商品详情:</span>
          <div dangerouslySetInnerHTML={{ __html: detail }}></div>
        </List.Item>
      </List>
    </Card>
  );
};

export default ProductDetail;